import { useCallback, useEffect, useState } from 'react'
import { useSize, useScroll } from 'ahooks'
import { limit } from '@/utils'

/**
 * @description 滚动到底部监听
 * @param {function} callback 回调函数(不要使用匿名函数)
 * @param {number} offset 距离底部多少px时,就触发
 * @param {number} delay 触发的节流延迟(ms)
 */
export default function useReachBottom(callback = console.log, { offset = 100, delay = 500 } = {}) {
  const viewSize = useSize(window.document.documentElement)
  const contentSize = useSize(window.document.body)
  const scroll = useScroll(document)
  const [prevTime, setTime] = useState(Date.now())

  const onScroll = useCallback(
    (scrollTop = 0) => {
      if (Number.isNaN(scrollTop) || !viewSize || !contentSize || typeof callback !== 'function') {
        return
      }

      offset = limit(offset, { min: 0 })
      delay = limit(delay, { min: 0, max: 1000 })

      const bottom = contentSize.height - viewSize.height - scrollTop
      const currTime = Date.now()
      if (bottom > 0 && bottom < offset && currTime - prevTime > delay) {
        setTime(currTime)
        callback(bottom)
      }
    },
    [prevTime, viewSize, contentSize, callback]
  )

  useEffect(() => {
    onScroll(scroll.top)
  }, [onScroll, scroll.top])
}
